<?php

namespace app\health\job;

use app\health\model\HealthGoods;
use app\health\model\HealthGoodsAttr;
use app\health\model\HealthOrder;
use think\queue\Job;

/**
 * 订单自动操作
 * @Author 张旭鹏
 * @DateTime 2023-06-26
 */
class OrderAutoOper extends BaseJob
{

    /**
     * 订单自动取消
     * @param \think\queue\Job $job
     * @param [type] $data
     * @Author 张旭鹏
     * @DateTime 2023-06-26
     */
    public function autoClose(Job $job, $data)
    {
        // 删除 job
        $job->delete();
        try {
            $queueData = $data['order'];
            $order = HealthOrder::where('id', $queueData['id'])->find();
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            if ($order->status == 1) {
                //执行取消订单逻辑
                HealthOrder::cancelOrder($queueData['id'], $order['user_id']);
            }
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoClose' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

    /**
     * 订单完成自动同步购买数量
     * Undocumented function
     * @param \think\queue\Job $job
     * @param [type] $data
     * @Author 张旭鹏
     * @DateTime 2023-06-29
     */
    public function autoGoodsSales(Job $job, $data)
    {
        $job->delete();
        $order = HealthOrder::where('id', $data['order_id'])->with(['orderGoods'])->find();
        if ($order) {
            foreach ($order->orderGoods as $item) {
                HealthGoods::where('id', $item['goods_id'])->setInc('sales_total', $item['number']);
                HealthGoodsAttr::where('id', $item['goods_attr_id'])->setInc('sales_total', $item['number']);
            }
        }
    }
}
